using GroupSix.Domain.Repositories;
using GroupSix.Domain.Entity.App;
using GroupSix.Domain.common;
using GroupSix.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace GroupSix.Infrastructure.Reposoitories;

/// <summary>
/// 文章仓储实现
/// </summary>
public class ArticleRepository : EfRepository<GsArticle>, IArticleRepository
{
    public ArticleRepository(GroupSixDbContext context) : base(context)
    {
    }

    /// <summary>
    /// 获取文章列表
    /// </summary>
    public async Task<PageResult<GsArticle>> GetArticlesAsync(string? keyword, Guid? categoryId, string? status, string? authorName, int page = 1, int pageSize = 20)
    {
        var queryable = _tb.AsQueryable();

        // 过滤已删除的记录
        queryable = queryable.Where(a => !a.IsDeleted);

        // 应用查询条件
        if (!string.IsNullOrEmpty(keyword))
        {
            queryable = queryable.Where(a => a.Title.Contains(keyword) || a.Summary.Contains(keyword));
        }

        if (categoryId.HasValue)
        {
            queryable = queryable.Where(a => a.CategoryId == categoryId.Value);
        }

        if (!string.IsNullOrEmpty(status))
        {
            queryable = queryable.Where(a => a.Status == status);
        }

        if (!string.IsNullOrEmpty(authorName))
        {
            queryable = queryable.Where(a => a.AuthorName.Contains(authorName));
        }

        // 按排序权重和创建时间倒序排列
        queryable = queryable.OrderByDescending(a => a.SortWeight)
                            .ThenByDescending(a => a.CreatedAt);

        var totalCount = await queryable.CountAsync();

        var items = await queryable
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return new PageResult<GsArticle>
        {
            Items = items,
            TotalCount = totalCount,
            PageIndex = page,
            PageSize = pageSize
        };
    }

    /// <summary>
    /// 根据标签获取文章列表
    /// </summary>
    public async Task<List<GsArticle>> GetArticlesByTagAsync(string tag, int page = 1, int pageSize = 20)
    {
        var queryable = _tb.Where(a => a.Tags.Contains(tag) && !a.IsDeleted)
                          .OrderByDescending(a => a.SortWeight)
                          .ThenByDescending(a => a.CreatedAt);

        return await queryable
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    /// <summary>
    /// 统计分类下的文章数量
    /// </summary>
    public async Task<int> CountByCategoryAsync(Guid categoryId)
    {
        return await _tb.Where(a => a.CategoryId == categoryId && !a.IsDeleted).CountAsync();
    }

    /// <summary>
    /// 获取文章分类列表
    /// </summary>
    public async Task<List<GsArticleCategory>> GetCategoriesAsync()
    {
        return await _db.GsArticleCategories
            .OrderBy(c => c.SortOrder)
            .ThenBy(c => c.Name)
            .ToListAsync();
    }
} 